/*
 *
 * This is a VoIP Application designed for local-network usage for voice and
 * messaging
 * Copyright (C) 2012  Imran M Yousuf (imyousuf@smitsol.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.smitsol.voip.server;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.smartitengineering.cms.binder.guice.Initializer;
import com.smartitengineering.dao.hbase.ddl.HBaseTableGenerator;
import com.smartitengineering.dao.hbase.ddl.config.json.ConfigurationJsonParser;
import com.smartitengineering.dao.impl.hbase.HBaseConfigurationFactory;
import com.smiitsol.voip.api.MasterModule;
import com.smitsol.voip.api.API;
import com.smitsol.voip.api.impl.APIModule;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.MasterNotRunningException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author imyousuf
 */
public class SipServletContextListener implements ServletContextListener {

  private final transient Logger logger = LoggerFactory.getLogger(getClass());

  public void contextInitialized(ServletContextEvent sce) {
    Configuration config = HBaseConfigurationFactory.getConfigurationInstance();
    final ClassLoader classLoader = Initializer.class.getClassLoader();
    try {
      new HBaseTableGenerator(ConfigurationJsonParser.getConfigurations(classLoader.getResourceAsStream(
          "com/smartitengineering/cms/spi/impl/schema.json")), config, false).generateTables();
    }
    catch (MasterNotRunningException ex) {
      logger.error("Master could not be found!", ex);
    }
    catch (Exception ex) {
      logger.error("Could not create table!", ex);
    }



    Initializer.init();
    Injector injector = Guice.createInjector(new MasterModule(), new APIModule());
    sce.getServletContext().setAttribute(API.INJECTOR_CONTEXT_NAME, injector);
    sce.getServletContext().setAttribute(API.API_CONTEXT_NAME, injector.getInstance(API.class));
  }

  public void contextDestroyed(ServletContextEvent sce) {
  }
}
